﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClientTools.TestProject
{
    public class CleanVersionScript
    {
        DCDataContext dc = new DCDataContext();
        private log4net.ILog log = log4net.LogManager.GetLogger(typeof(CleanVersionScript));

        public void Go()
        {
            log4net.Config.XmlConfigurator.Configure();

            log.Info("Started...");
            List<umbracoNode> umbracoNodes = (from x in dc.umbracoNodes where x.nodeObjectType.Value.ToString() == "c66ba18e-eaf3-4cff-8a22-41b16d66a972" select x).ToList();
            log.Info(string.Format("Found {0} umbracoNodes", umbracoNodes.Count));

            foreach (umbracoNode node in umbracoNodes)
            {
                List<cmsDocument> documents = (from x in dc.cmsDocuments where x.nodeId == node.id select x).ToList();
                log.Info(string.Format("Found {0} documents for node {1}", documents.Count, node.id));
                cmsDocument publishedDocument = (from x in documents where x.published == true select x).FirstOrDefault();
                if (publishedDocument == null)
                {
                    log.Info(string.Format("No published document found for node {0}", node.id));
                    continue;
                }
                List<cmsContentVersion> versions = (from x in dc.cmsContentVersions where x.ContentId == node.id select x).ToList();
                log.Info(string.Format("Found {0} versions for node {1}", versions.Count, node.id));

                foreach (cmsDocument document in documents)
                {
                    if (document.published == true || document.releaseDate >= publishedDocument.releaseDate || document.newest) continue;
                    cmsDocument doc = (from x in dc.cmsDocuments where x.versionId == document.versionId && x.nodeId == document.nodeId select x).FirstOrDefault();
                    // get the version of this document
                    cmsContentVersion version = (from x in dc.cmsContentVersions where x.VersionId == document.versionId select x).FirstOrDefault();
                    foreach (cmsPropertyData propData in (from x in dc.cmsPropertyDatas where x.versionId == version.VersionId select x))
                    {
                        dc.cmsPropertyDatas.DeleteOnSubmit(propData);                        
                    }
                    dc.cmsContentVersions.DeleteOnSubmit(version);
                    dc.cmsDocuments.DeleteOnSubmit(doc);
                    dc.SubmitChanges();
                    log.Info(string.Format("A version is cleande for node {0}", node.id));
                }
                log.Info(string.Format("Node {0} cleaned", node.id));
                //System.GC.Collect();
            }

            Console.ReadKey();
        }
    }
}
